<template>
    <el-card shadow="never" class="border-0">
        <!-- 搜索 -->
        <el-form :model="searchForm" label-width="80px" class="mb-3" size="small">
            <el-row :gutter="20">
                <el-col :span="4">
                    <el-form-item label="课程名称">
                        <el-input v-model="searchForm.title" placeholder="课程名称" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="15">
                    <div class="flex items-center justify-end">
                        <el-button type="primary" @click="initTableData(1)">搜索</el-button>
                        <el-button @click="resetSearchForm">重置</el-button>
                    </div>
                </el-col>
            </el-row>
        </el-form>


        <!-- 新增|刷新 -->
        <div class="flex items-center justify-between mb-4">
            <div>
                <el-button type="primary" size="small" @click="handleCreate">新增</el-button>
            </div>

            <el-tooltip effect="dark" content="刷新数据" placement="top">
                <el-button text @click="initTableData">
                    <el-icon :size="20">
                        <Refresh />
                    </el-icon>
                </el-button>
            </el-tooltip>
        </div>

        <!-- 表格数据 -->
        <el-table :data="tableData" stripe style="width: 100%" v-loading="loading">

            <el-table-column label="课程类别" align="center" show-overflow-tooltip>
                <template #default="{ row }">
                    {{ row.categoryName }}
                </template>
            </el-table-column>

            <el-table-column label="课程标题" align="center" show-overflow-tooltip>
                <template #default="{ row }">
                    {{ row.title }}
                </template>
            </el-table-column>

            <el-table-column label="VDR MODEL" align="center" show-overflow-tooltip>
                <template #default="{ row }">
                    {{ row.model }}
                </template>
            </el-table-column>

            <el-table-column label="课程描述" align="center" show-overflow-tooltip>
                <template #default="{ row }">
                    {{ row.description }}
                </template>
            </el-table-column>

            <el-table-column label="课程图片" align="center">
                <template #default="{ row }">
                    <el-image style="width: 60px; height: 60px" :preview-teleported="true" class="images"
                        :hide-on-click-modal=true :src="row.url" :zoom-rate="1.2" :preview-src-list="[row.url]"
                        :initial-index="1" fit="cover">
                    </el-image>
                </template>
            </el-table-column>

            <el-table-column label="适用人群" align="center">
                <template #default="{ row }">
                    {{ formatRoleType(row.roleType) }}
                </template>
            </el-table-column>

            <el-table-column label="课程节数" align="center">
                <template #default="{ row }">
                    {{ row.classes }}
                </template>
            </el-table-column>

            <el-table-column label="预估用时" align="center">
                <template #default="{ row }">
                    {{ msToTime(row.time) }}
                </template>
            </el-table-column>

            <el-table-column label="状态" align="center">
                <template #default="{ row }">
                    {{ row.state == '0' ? '下架' : '上架' }}
                </template>
            </el-table-column>

            <el-table-column label="创建时间" align="center">
                <template #default="{ row }">
                    {{ dateFormatter(row.createTime) }}
                </template>
            </el-table-column>

            <el-table-column label="操作" width="320" align="center">
                <template #default="scope">
                    <small v-if="scope.row.super == 1" class="text-sm text-gray-500">暂无操作</small>
                    <div v-else>
                        <el-button v-if="scope.row.state == '0'" type="primary" size="small" text
                            @click="handleChangeState(scope.row, 1)">上架</el-button>
                        <el-button v-else type="primary" size="small" text
                            @click="handleChangeState(scope.row, 0)">下架</el-button>
                        <el-button type="primary" size="small" text :disabled="scope.row.state == '1'"
                            @click="handleEdit(scope.row)">修改</el-button>
                        <el-button type="primary" size="small" text :disabled="scope.row.state == '1'"
                            @click="handleAddClass(scope.row)">课时</el-button>
                        <el-button type="primary" size="small" text :disabled="scope.row.state == '1'"
                            @click="handleAddFiles(scope.row)">附件</el-button>
                        <el-popconfirm title="是否要删除该课程？" confirmButtonText="确认" cancelButtonText="取消"
                            @confirm="handleDelete(scope.row.id)">
                            <template #reference>
                                <el-button text type="primary" size="small"
                                    :disabled="scope.row.state == '1'">删除</el-button>
                            </template>
                        </el-popconfirm>
                    </div>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <div class="flex items-center justify-center mt-5">
            <el-pagination background layout="prev, pager ,next" :total="total" :current-page="currentPage"
                :page-size="limit" @current-change="initTableData" />
        </div>

        <!-- 新增|修改弹窗 -->
        <FormDrawer ref="formDrawerRef" :title="drawerTitle" @submit="handleSubmit">
            <el-form :model="form" ref="formRef" :rules="rules" label-width="120px" :inline="false">
                <el-form-item label="课程类别" prop="categoryId">
                    <el-tree-select v-model="form.categoryId" :data="categoryData" :props="{
                        label: 'name',
                        value: 'id',
                        children: 'children',
                    }" placeholder="课程类别">
                    </el-tree-select>
                </el-form-item>

                <el-form-item label="适用人群" prop="roleType">
                    <el-radio-group v-model="form.roleType">
                        <el-radio value="0">所有人</el-radio>
                        <el-radio value="1">工程师</el-radio>
                        <el-radio value="2">船员</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="课程标题" prop="title">
                    <el-input v-model="form.title" placeholder="课程标题"></el-input>
                </el-form-item>

                <el-form-item v-if="form.roleType != '2'" label="VDR MODEL" prop="model">
                    <el-input v-model="form.model" placeholder="VDR MODEL"></el-input>
                </el-form-item>

                <el-form-item label="课程描述" prop="description">
                    <el-input v-model="form.description" placeholder="课程描述"></el-input>
                </el-form-item>

                <el-form-item label="课程图片" prop="files">
                    <el-upload class="upload-demo" :class="hideUpload ? 'hide' : ''" list-type="picture-card"
                        ref="upload" accept=".jpg,.png" action="" :limit="1" :on-change="fileChange"
                        :file-list="form.files" :before-upload="beforeUpload" :on-exceed="handleExceed"
                        :on-remove="handleRemove" :http-request="uploadSubmit" :auto-upload="false">
                        <el-icon>
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
            </el-form>
        </FormDrawer>
    </el-card>


    <!-- 课程附件 -->
    <el-dialog v-model="dialogTableVisible_courseFiles" :title="dialogTable_courseFiles_title" width="700" align-center>
        <CourseFiles v-if="dialogTableVisible_courseFiles" :courseId="currCourseFiles_courseId" />
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="dialogTableVisible_courseFiles = false">
                    关闭
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue"
import FormDrawer from "~/components/FormDrawer.vue";
import { toast, toastWarn } from "~/composables/util"
import { dateFormatter, msToTime } from '~/utils/common.js'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { checkContainsChinese } from '~/utils/validate.js'
import CourseFiles from "~/components/course-files.vue";
import { api_category_tree, api_course_list, api_course_add, api_course_update, api_course_changeState, api_course_delete } from "~/api/exam/categoryApi";

//store存储
const store = useStore()

// 全局路由
const router = useRouter()

// 课程类别树形
const categoryData = ref(null)

// 表格分页数据
const tableData = ref([])
const loading = ref(false)
const currentPage = ref(1)
const total = ref(0)
const limit = ref(10)


// 查询条件
const searchForm = reactive({
    title: null,
    page: currentPage.value,
    size: limit.value,
})
// 重置搜索框
const resetSearchForm = () => {
    searchForm.title = null
    initTableData(1)
}

// 生命周期函数
onMounted(() => {

    //获取树形结构字典数据
    initCategoryData()

    //初始化列表数据
    initTableData()
})

// 获取数据
function initCategoryData() {
    api_category_tree()
        .then(res => {
            categoryData.value = res
        })
}

// 表单部分
// 是否是编辑弹窗
const editId = ref(0)
const drawerTitle = computed(() => editId.value ? "修改" : "新增")
const formDrawerRef = ref(null)
const formRef = ref(null)
const form = reactive({
    categoryId: null,
    title: null,
    model: null,
    description: null,
    //0:全部 1:工程师 2:船员，默认: 0
    roleType: "0",
    files: []
})

//执行表单校验
const rules = {
    categoryId: [
        { required: true, message: '课程类别不能为空', trigger: 'change' }
    ],
    title: [
        { required: true, message: '课程标题不能为空', trigger: 'change' }
    ],
    model: [
        { required: true, message: 'VDR MODEL不能为空', trigger: 'change' },
        { required: true, validator: checkContainsChinese, trigger: 'change' }
    ],
    description: [
        { required: true, message: '课程描述不能为空', trigger: 'change' }
    ],
    files: [
        { required: true, message: '课程图片不能为空', trigger: 'change' }
    ],
    roleType: [
        { required: true, message: '适用人群不能为空', trigger: 'change' }
    ]
}

function formatRoleType(roleType) {
    if (roleType == '0') {
        return '全部'
    } else if (roleType == '1') {
        return '工程师'
    } else if (roleType == '2') {
        return '船员'
    } else {
        return '-'
    }
}

//提交表单
const handleSubmit = () => {
    //表单校验
    formRef.value.validate((valid) => {
        if (!valid) return
        //新增
        if (editId.value == 0) {
            //触发文件上传
            upload.value.submit();
        } else {
            if (editImgChanged.value == true) {
                //触发文件上传
                upload.value.submit();
            } else {
                let paramIo = new FormData()// FormData 对象
                paramIo.append('id', editId.value)
                paramIo.append('title', form.title)
                if (form.roleType != '2') {
                    paramIo.append('model', form.model)
                }
                paramIo.append('description', form.description)
                paramIo.append('categoryId', form.categoryId)
                paramIo.append('roleType', form.roleType)
                //loading
                formDrawerRef.value.showLoading()
                const fun = api_course_update(editId.value, paramIo)
                fun.then(res => {
                    toast(drawerTitle.value + "成功")
                    //清空file文件
                    upload.value.clearFiles();
                    //修改刷新当前页，新增刷新第一页
                    initTableData(editId.value ? false : 1)
                    formDrawerRef.value.close()
                })
                    .finally(() => {
                        //close loading
                        formDrawerRef.value.hideLoading()
                    })
            }
        }
    })
}

// 新增按钮点击事件
const handleCreate = () => {
    //修改标记置为0
    editId.value = 0
    hideUpload.value = false
    resetForm({
        categoryId: null,
        title: null,
        model: null,
        description: null,
        //0:全部 1:工程师 2:船员，默认: 0
        roleType: "0",
        files: []
    })
    //打开弹窗
    formDrawerRef.value.open()
}

// 重置表单
function resetForm(row = false) {
    if (formRef.value) formRef.value.resetFields()
    if (row) {
        for (const key in form) {
            form[key] = row[key]
        }
    }
}

// 上传组件 -------------------------------------------
//上传组件
const upload = ref(null)
const hideUpload = ref(false)
const editImgChanged = ref(false)

// 文件改变
const fileChange = (file, fileList) => {
    form.files = fileList;
    hideUpload.value = true
    editImgChanged.value = true
    // console.log(JSON.stringify(form.files))
}
// 文件超出个数限制
const handleExceed = (file, fileList) => {
    toastWarn('只能选择一个文件');
}
// 文件移除
const handleRemove = (file, fileList) => {
    form.files = [];
    hideUpload.value = false
}
// 上传前 文件校验
const beforeUpload = (file) => {
    //console.log("==============" + JSON.stringify(file))
    const isLt2M = file.size / 1024 / 1024 < 10
    if (!isLt2M) {
        toastWarn('上传文件大小不能超过 10MB!')
        return false;
    }
    return true;
}
//提交上的文件
const uploadSubmit = (param) => {
    let fileObj = param.file// 相当于input里取得的files
    let paramIo = new FormData()// FormData 对象
    paramIo.append('id', editId.value)// 主键ID
    paramIo.append('files', fileObj)// 文件对象
    paramIo.append('title', form.title)
    if (form.roleType != '2') {
        paramIo.append('model', form.model)
    }
    paramIo.append('description', form.description)
    paramIo.append('categoryId', form.categoryId)
    paramIo.append('roleType', form.roleType)
    //loading
    formDrawerRef.value.showLoading()
    const fun = editId.value == 0 ? api_course_add(paramIo) : api_course_update(editId.value, paramIo)
    fun.then(res => {
        toast(drawerTitle.value + "成功")
        //清空file文件
        upload.value.clearFiles();
        //修改刷新当前页，新增刷新第一页
        initTableData(editId.value ? false : 1)
        formDrawerRef.value.close()
    })
        .finally(() => {
            //close loading
            formDrawerRef.value.hideLoading()
        })
}
// 上传组件 -------------------------------------------


// 获取数据
function initTableData(p = null) {
    //指定页码是否为空
    if (typeof p == "number") {
        currentPage.value = p
    }

    loading.value = true
    searchForm.page = currentPage.value

    api_course_list(searchForm)
        .then(res => {
            if (res) {
                tableData.value = res.records
                total.value = Number(res.total)
            } else {
                tableData.value = []
                total.value = 0
            }
        })
        .finally(() => {
            loading.value = false
        })
}

// 编辑
const handleEdit = (row) => {
    editId.value = row.id
    resetForm(row)
    //回显图片
    form.files = [{ url: row.url }]
    hideUpload.value = true
    editImgChanged.value = false
    formDrawerRef.value.open()
}

// 课时
const handleAddClass = (row) => {
    store.commit("SetCourseId", row.id)
    //跳转界面
    router.push({
        path: '/examCourseClass',
    });
}


//课程附件---------------
const dialogTableVisible_courseFiles = ref(false)
const dialogTable_courseFiles_title = ref(null)
const currCourseFiles_courseId = ref(null)
//课程附件---------------
// 附件
const handleAddFiles = (row) => {
    dialogTable_courseFiles_title.value = "课程附件"
    currCourseFiles_courseId.value = row.id
    dialogTableVisible_courseFiles.value = true
}

// 上架下架
const handleChangeState = (row, state) => {
    loading.value = true
    api_course_changeState(row.id, state).then(res => {
        toast("操作成功")
        initTableData()
    })
        .finally(() => {
            loading.value = false
        })
}


// 删除
const handleDelete = (id) => {
    loading.value = true
    api_course_delete(id).then(res => {
        toast("删除成功")
        initTableData()
    })
        .finally(() => {
            loading.value = false
        })
}
</script>

<style scoped>
.hide ::v-deep .el-upload--picture-card {
    display: none;
}
</style>